import sys
import os
import cv2
import imageio
import logging
from collections import OrderedDict
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
    QPushButton, QSlider, QLabel, QFileDialog, QLineEdit, QMessageBox, QProgressBar,
    QMenuBar, QMenu, QStatusBar, QAction, QDockWidget, QFormLayout, QCheckBox, QGraphicsDropShadowEffect
)
from PyQt5.QtWidgets import QDialog
from PyQt5.QtCore import Qt, QTimer, QSize, QThread, pyqtSignal, QSettings, QTranslator
from PyQt5.QtGui import QImage, QPixmap, QKeySequence, QIcon
from PyQt5.QtWidgets import QSizePolicy, QShortcut
from app.utils.logging_utils import setup_logging
from app.utils.theme_utils import LIGHT_THEME_CSS, DARK_THEME_CSS
from app.widgets.custom_button import CustomButton
from app.dialogs.settings_dialog import SettingsDialog
from app.models.data_model import LRUCache
from app.controllers.main_controller import ExportGifThread

class VideoToGifConverter(QMainWindow):
    def __init__(self):
        super().__init__()
        self.settings = QSettings("Common", "VideoToGifConverter")
        self.load_window_state()
        self.setWindowTitle("Video to GIF Converter")
        self.initUI()

    def load_window_state(self):
        self.resize(self.settings.value("window/size", QSize(1200, 800)))
        self.move(self.settings.value("window/position", self.pos()))

    def save_window_state(self):
        self.settings.setValue("window/size", self.size())
        self.settings.setValue("window/position", self.pos())

    def closeEvent(self, event):
        self.save_window_state()
        event.accept()

    def initUI(self):
        self.video_path = None
        self.cap = None
        self.timer = QTimer()
        self.current_frame = 0
        self.fps = 0
        self.total_frames = 0
        self.is_slider_pressed = False
        self.frame_cache = LRUCache(200)
        self.export_thread = None
        self.is_dark_theme = False
        self.language = "zh"

        self.createMenuBar()
        self.createToolBar()
        self.createMainContent()
        self.createSideBar()
        self.createStatusBar()
        self.applyTheme()

        QShortcut(QKeySequence("Space"), self, self.play_pause_video)
        QShortcut(QKeySequence("Left"), self, self.rewind_video)
        QShortcut(QKeySequence("Right"), self, self.forward_video)
        QShortcut(QKeySequence("Ctrl+O"), self, self.upload_video)
        QShortcut(QKeySequence("Ctrl+S"), self, self.export_gif)
        QShortcut(QKeySequence("Esc"), self, self.toggleFullScreen)

    def createMenuBar(self):
        menubar = self.menuBar()
        file_menu = menubar.addMenu('文件' if self.language == "zh" else 'File')
        open_action = QAction('打开视频' if self.language == "zh" else 'Open Video', self)
        open_action.triggered.connect(self.upload_video)
        file_menu.addAction(open_action)
        exit_action = QAction('退出' if self.language == "zh" else 'Exit', self)
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)

        edit_menu = menubar.addMenu('编辑' if self.language == "zh" else 'Edit')
        reset_action = QAction('复位' if self.language == "zh" else 'Reset', self)
        reset_action.triggered.connect(self.reset_video)
        edit_menu.addAction(reset_action)

        theme_menu = menubar.addMenu('主题' if self.language == "zh" else 'Theme')
        light_theme_action = QAction('浅色主题' if self.language == "zh" else 'Light Theme', self)
        light_theme_action.triggered.connect(lambda: self.setTheme(False))
        dark_theme_action = QAction('深色主题' if self.language == "zh" else 'Dark Theme', self)
        dark_theme_action.triggered.connect(lambda: self.setTheme(True))
        theme_menu.addAction(light_theme_action)
        theme_menu.addAction(dark_theme_action)

        language_menu = menubar.addMenu('语言' if self.language == "zh" else 'Language')
        chinese_action = QAction('中文', self)
        chinese_action.triggered.connect(lambda: self.setLanguage("zh"))
        english_action = QAction('English', self)
        english_action.triggered.connect(lambda: self.setLanguage("en"))
        language_menu.addAction(chinese_action)
        language_menu.addAction(english_action)

        # 添加帮助菜单
        help_menu = menubar.addMenu('帮助' if self.language == "zh" else 'Help')
        about_action = QAction('关于' if self.language == "zh" else 'About', self)
        about_action.triggered.connect(self.show_about_dialog)
        help_menu.addAction(about_action)

    def show_about_dialog(self):
        """显示关于对话框"""
        about_dialog = QDialog(self)
        about_dialog.setWindowTitle('关于作者' if self.language == "zh" else 'About Author')
        about_dialog.setFixedSize(450, 550)  # 设置对话框大小

        # 主布局
        layout = QVBoxLayout()
        layout.setSpacing(20)  # 设置控件间距
        layout.setContentsMargins(20, 20, 20, 20)  # 设置边距

        # 标题
        title_label = QLabel('关于作者' if self.language == "zh" else 'About Author')
        title_label.setStyleSheet("""
            font-size: 24px;
            font-weight: bold;
            color: #0078d7;
            text-align: center;
            padding-bottom: 10px;
            border-bottom: 2px solid #0078d7;
        """)
        layout.addWidget(title_label)

        # 作者头像
        author_icon_path = os.path.join("app", "resources", "icons", "avatar.png")  # 假设头像文件为 author_icon.png
        if os.path.exists(author_icon_path):
            author_icon_label = QLabel()
            author_icon_label.setPixmap(QPixmap(author_icon_path).scaled(120, 120, Qt.KeepAspectRatio, Qt.SmoothTransformation))
            author_icon_label.setAlignment(Qt.AlignCenter)
            author_icon_label.setStyleSheet("margin-bottom: 20px;")
            layout.addWidget(author_icon_label)
        else:
            print(f"作者头像未找到: {author_icon_path}")

        # 作者信息
        author_info_layout = QVBoxLayout()
        author_info_layout.setSpacing(10)

        # 作者姓名
        author_name_label = QLabel('作者姓名: 凌云' if self.language == "zh" else 'Author Name: 凌云')
        author_name_label.setStyleSheet("font-size: 16px; color: #333333; font-weight: bold;")
        author_info_layout.addWidget(author_name_label)

        # 作者简介
        author_bio_label = QLabel('你好, 我是 凌云，一名热爱技术的开发者，专注于探索前沿技术与创新实践。在这里，我将分享我的编程心得、项目经验和成长故事，与大家一起在代码的世界里追逐青春梦想。技术无界，未来无限，让我们一起极客青春，玩转技术！' if self.language == "zh" else """Hello, I am Ling Yun, a developer with a passion for technology, dedicated to exploring cutting-edge techniques and innovative practices. Here, I will share my insights on programming, project experiences, and growth stories, engaging with everyone in pursuing youthful dreams within the world of code. Technology knows no bounds, and the future is limitless. Let's together geek out our youth and master technology!.""")
        author_bio_label.setStyleSheet("font-size: 14px; color: #555555;")
        author_bio_label.setWordWrap(True)  # 允许换行
        author_info_layout.addWidget(author_bio_label)

        # 软件信息
        software_info_layout = QVBoxLayout()
        software_info_layout.setSpacing(10)

        # 软件名称
        software_name_label = QLabel('软件名称: Video to GIF Converter' if self.language == "zh" else 'Software Name: Video to GIF Converter')
        software_name_label.setStyleSheet("font-size: 16px; color: #333333; font-weight: bold;")
        software_info_layout.addWidget(software_name_label)

        # 软件版本
        software_version_label = QLabel('软件版本: 1.0.0' if self.language == "zh" else 'Version: 1.0.0')
        software_version_label.setStyleSheet("font-size: 14px; color: #555555;")
        software_info_layout.addWidget(software_version_label)

        # 开发团队
        team_label = QLabel('开发团队: 凌云' if self.language == "zh" else 'Development Team: 凌云')
        team_label.setStyleSheet("font-size: 14px; color: #555555;")
        software_info_layout.addWidget(team_label)

        # 开发时间
        development_time_label = QLabel('开发时间: 2024-01-01' if self.language == "zh" else 'Development Time: 2024-01-01')
        development_time_label.setStyleSheet("font-size: 14px; color: #555555;")
        software_info_layout.addWidget(development_time_label)

        # 联系方式
        contact_layout = QVBoxLayout()
        contact_layout.setSpacing(10)

        # 邮箱
        email_label = QLabel('邮箱: 3942007626@qq.com' if self.language == "zh" else 'Email: 3942007626@qq.com')
        email_label.setStyleSheet("font-size: 14px; color: #555555;")
        contact_layout.addWidget(email_label)

        # 网站
        website_label = QLabel('网站: https://i.csdn.net/#/user-center/profile?spm=1010.2135.3001.5111' if self.language == "zh" else 'Website: https://i.csdn.net/#/user-center/profile?spm=1010.2135.3001.5111')
        website_label.setStyleSheet("font-size: 14px; color: #555555;")
        website_label.setOpenExternalLinks(True)  # 允许点击链接
        contact_layout.addWidget(website_label)

        # 社交媒体
        social_media_label = QLabel('社交媒体: [GitHub](https://github.com/yourname)' if self.language == "zh" else 'Social Media: [GitHub](https://github.com/yourname)')
        social_media_label.setStyleSheet("font-size: 14px; color: #555555;")
        social_media_label.setOpenExternalLinks(True)  # 允许点击链接
        contact_layout.addWidget(social_media_label)

        # 将作者信息、软件信息和联系方式添加到主布局
        layout.addLayout(author_info_layout)
        layout.addLayout(software_info_layout)
        layout.addLayout(contact_layout)

        # 按钮布局
        button_layout = QHBoxLayout()
        button_layout.setSpacing(20)

        # 确定按钮
        ok_button = QPushButton('确定' if self.language == "zh" else 'OK', about_dialog)
        ok_button.setStyleSheet("""
            QPushButton {
                background-color: #0078d7;
                border: 1px solid #005bb5;
                border-radius: 5px;
                padding: 10px 20px;
                color: #ffffff;
                font-size: 14px;
                font-weight: bold;
                min-width: 100px;
            }
            QPushButton:hover {
                background-color: #005bb5;
                border-color: #004080;
            }
            QPushButton:pressed {
                background-color: #004080;
            }
        """)
        ok_button.clicked.connect(about_dialog.close)
        button_layout.addWidget(ok_button)

        # 取消按钮
        cancel_button = QPushButton('取消' if self.language == "zh" else 'Cancel', about_dialog)
        cancel_button.setStyleSheet("""
            QPushButton {
                background-color: #cccccc;
                border: 1px solid #999999;
                border-radius: 5px;
                padding: 10px 20px;
                color: #333333;
                font-size: 14px;
                font-weight: bold;
                min-width: 100px;
            }
            QPushButton:hover {
                background-color: #bbbbbb;
                border-color: #888888;
            }
            QPushButton:pressed {
                background-color: #aaaaaa;
            }
        """)
        cancel_button.clicked.connect(about_dialog.close)
        button_layout.addWidget(cancel_button)

        # 将按钮布局添加到主布局
        layout.addLayout(button_layout)

        # 设置对话框布局
        about_dialog.setLayout(layout)
        about_dialog.exec_()
    


    
    def createToolBar(self):
        self.toolbar = self.addToolBar('工具栏' if self.language == "zh" else 'Toolbar')
        self.play_button = QPushButton("▶")
        self.play_button.setToolTip("播放" if self.language == "zh" else "Play")
        self.play_button.clicked.connect(self.play_video)
        self.play_button.setStyleSheet("""
            QPushButton {
                background-color: #E3F2FD;
                color: #1976D2;
                border: 1px solid #90CAF9;
                padding: 5px;
                border-radius: 4px;
                font-size: 14px;
                min-width: 30px;
                min-height: 30px;
            }
            QPushButton:hover {
                background-color: #BBDEFB;
                border: 1px solid #64B5F6;
            }
            QPushButton:pressed {
                background-color: #90CAF9;
            }
        """)
        shadow = QGraphicsDropShadowEffect()
        shadow.setBlurRadius(10)
        shadow.setColor(Qt.gray)
        shadow.setOffset(3, 3)
        self.play_button.setGraphicsEffect(shadow)
        self.toolbar.addWidget(self.play_button)

        self.pause_button = QPushButton("⏸")
        self.pause_button.setToolTip("暂停" if self.language == "zh" else "Pause")
        self.pause_button.clicked.connect(self.pause_video)
        self.pause_button.setStyleSheet("""
            QPushButton {
                background-color: #E3F2FD;
                color: #1976D2;
                border: 1px solid #90CAF9;
                padding: 5px;
                border-radius: 4px;
                font-size: 14px;
                min-width: 30px;
                min-height: 30px;
            }
            QPushButton:hover {
                background-color: #BBDEFB;
                border: 1px solid #64B5F6;
            }
            QPushButton:pressed {
                background-color: #90CAF9;
            }
        """)
        shadow = QGraphicsDropShadowEffect()
        shadow.setBlurRadius(10)
        shadow.setColor(Qt.gray)
        shadow.setOffset(3, 3)
        self.pause_button.setGraphicsEffect(shadow)
        self.toolbar.addWidget(self.pause_button)

        self.rewind_button = QPushButton("⏪")
        self.rewind_button.setToolTip("快退3s" if self.language == "zh" else "Rewind 3s")
        self.rewind_button.clicked.connect(self.rewind_video)
        self.rewind_button.setStyleSheet("""
            QPushButton {
                background-color: #E3F2FD;
                color: #1976D2;
                border: 1px solid #90CAF9;
                padding: 5px;
                border-radius: 4px;
                font-size: 14px;
                min-width: 30px;
                min-height: 30px;
            }
            QPushButton:hover {
                background-color: #BBDEFB;
                border: 1px solid #64B5F6;
            }
            QPushButton:pressed {
                background-color: #90CAF9;
            }
        """)
        shadow = QGraphicsDropShadowEffect()
        shadow.setBlurRadius(10)
        shadow.setColor(Qt.gray)
        shadow.setOffset(3, 3)
        self.rewind_button.setGraphicsEffect(shadow)
        self.toolbar.addWidget(self.rewind_button)

        self.forward_button = QPushButton("⏩")
        self.forward_button.setToolTip("快进3s" if self.language == "zh" else "Forward 3s")
        self.forward_button.clicked.connect(self.forward_video)
        self.forward_button.setStyleSheet("""
            QPushButton {
                background-color: #E3F2FD;
                color: #1976D2;
                border: 1px solid #90CAF9;
                padding: 5px;
                border-radius: 4px;
                font-size: 14px;
                min-width: 30px;
                min-height: 30px;
            }
            QPushButton:hover {
                background-color: #BBDEFB;
                border: 1px solid #64B5F6;
            }
            QPushButton:pressed {
                background-color: #90CAF9;
            }
        """)
        shadow = QGraphicsDropShadowEffect()
        shadow.setBlurRadius(10)
        shadow.setColor(Qt.gray)
        shadow.setOffset(3, 3)
        self.forward_button.setGraphicsEffect(shadow)
        self.toolbar.addWidget(self.forward_button)

        self.reset_button = QPushButton("↺")
        self.reset_button.setToolTip("复位" if self.language == "zh" else "Reset")
        self.reset_button.clicked.connect(self.reset_video)
        self.reset_button.setStyleSheet("""
            QPushButton {
                background-color: #E3F2FD;
                color: #1976D2;
                border: 1px solid #90CAF9;
                padding: 5px;
                border-radius: 4px;
                font-size: 14px;
                min-width: 30px;
                min-height: 30px;
            }
            QPushButton:hover {
                background-color: #BBDEFB;
                border: 1px solid #64B5F6;
            }
            QPushButton:pressed {
                background-color: #90CAF9;
            }
        """)
        shadow = QGraphicsDropShadowEffect()
        shadow.setBlurRadius(10)
        shadow.setColor(Qt.gray)
        shadow.setOffset(3, 3)
        self.reset_button.setGraphicsEffect(shadow)
        self.toolbar.addWidget(self.reset_button)

    def createMainContent(self):
        main_widget = QWidget()
        main_layout = QVBoxLayout()
        self.video_label = QLabel("视频将在这里显示" if self.language == "zh" else "Video will be displayed here")
        self.video_label.setAlignment(Qt.AlignCenter)
        self.video_label.setStyleSheet("background-color: black; color: white;")
        self.video_label.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        main_layout.addWidget(self.video_label)

        # 美化进度条样式
        self.slider = QSlider(Qt.Horizontal)
        self.slider.setRange(0, 0)
        self.slider.sliderPressed.connect(self.slider_pressed)
        self.slider.sliderReleased.connect(self.slider_released)
        self.slider.sliderMoved.connect(self.slider_moved)
        self.slider.mousePressEvent = self.slider_mouse_press_event

        # 浅色主题样式
        self.light_slider_style = """
            QSlider::groove:horizontal {
                background-color: #e0e0e0;
                border: 1px solid #cccccc;
                height: 8px;
                border-radius: 4px;
            }
            QSlider::handle:horizontal {
                background-color: #0078d7;
                border: 1px solid #005bb5;
                width: 16px;
                height: 16px;
                border-radius: 8px;
                margin: -4px 0;
            }
            QSlider::sub-page:horizontal {
                background-color: #0078d7;
                border-radius: 4px;
            }
        """

        # 深色主题样式
        self.dark_slider_style = """
            QSlider::groove:horizontal {
                background-color: #444444;
                border: 1px solid #555555;
                height: 8px;
                border-radius: 4px;
            }
            QSlider::handle:horizontal {
                background-color: #0078d7;
                border: 1px solid #005bb5;
                width: 16px;
                height: 16px;
                border-radius: 8px;
                margin: -4px 0;
            }
            QSlider::sub-page:horizontal {
                background-color: #0078d7;
                border-radius: 4px;
            }
        """

        # 应用进度条样式
        self.applySliderTheme()

        main_layout.addWidget(self.slider)
        main_widget.setLayout(main_layout)
        self.setCentralWidget(main_widget)

    def applySliderTheme(self):
        if self.is_dark_theme:
            self.slider.setStyleSheet(self.dark_slider_style)
        else:
            self.slider.setStyleSheet(self.light_slider_style)
    def createSideBar(self):
        dock = QDockWidget("GIF 导出设置" if self.language == "zh" else "GIF Export Settings", self)
        dock.setFeatures(QDockWidget.NoDockWidgetFeatures)
        dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)
        side_widget = QWidget()
        side_layout = QFormLayout()
        self.start_second_input = QLineEdit("0.00")
        self.end_second_input = QLineEdit("10.00")
        self.width_input = QLineEdit("800")
        self.height_input = QLineEdit("450")
        self.frames_input = QLineEdit("109")
        self.fps_input = QLineEdit("10")
        self.optimize_checkbox = QCheckBox("优化 GIF" if self.language == "zh" else "Optimize GIF")
        self.export_button = QPushButton("导出GIF" if self.language == "zh" else "Export GIF")
        self.export_button.clicked.connect(self.export_gif)
        self.cancel_button = QPushButton("取消导出" if self.language == "zh" else "Cancel Export")
        self.cancel_button.clicked.connect(self.cancel_export)
        self.cancel_button.setEnabled(False)
        self.export_progress = QProgressBar()
        self.export_progress.setRange(0, 100)
        self.export_progress.setValue(0)
        self.export_progress.setFormat("已完成 %p%")
        self.light_style = """
            QProgressBar {
                border: 2px solid #90CAF9;
                border-radius: 5px;
                background-color: #E3F2FD;
                text-align: center;
                color: #1976D2;
                font-size: 12px;
            }
            QProgressBar::chunk {
                background: qlineargradient(
                    x1: 0, y1: 0, x2: 1, y2: 0,
                    stop: 0 #64B5F6, stop: 1 #42A5F5
                );
                border-radius: 3px;
            }
        """
        self.dark_style = """
            QProgressBar {
                border: 2px solid #1E88E5;
                border-radius: 5px;
                background-color: #0D47A1;
                text-align: center;
                color: #FFFFFF;
                font-size: 12px;
            }
            QProgressBar::chunk {
                background: qlineargradient(
                    x1: 0, y1: 0, x2: 1, y2: 0,
                    stop: 0 #42A5F5, stop: 1 #1E88E5
                );
                border-radius: 3px;
            }
        """
        self.applyProgressBarTheme()
        side_layout.addRow("起始秒数:" if self.language == "zh" else "Start Second:", self.start_second_input)
        side_layout.addRow("结束秒数:" if self.language == "zh" else "End Second:", self.end_second_input)
        side_layout.addRow("宽度:" if self.language == "zh" else "Width:", self.width_input)
        side_layout.addRow("高度:" if self.language == "zh" else "Height:", self.height_input)
        side_layout.addRow("帧数:" if self.language == "zh" else "Frames:", self.frames_input)
        side_layout.addRow("FPS:" if self.language == "zh" else "FPS:", self.fps_input)
        side_layout.addRow(self.optimize_checkbox)
        side_layout.addRow(self.export_button)
        side_layout.addRow(self.cancel_button)
        side_layout.addRow(self.export_progress)
        side_widget.setLayout(side_layout)
        dock.setWidget(side_widget)
        self.addDockWidget(Qt.RightDockWidgetArea, dock)

    def applyProgressBarTheme(self):
        if self.is_dark_theme:
            self.export_progress.setStyleSheet(self.dark_style)
        else:
            self.export_progress.setStyleSheet(self.light_style)

    def createStatusBar(self):
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.status_bar.showMessage("就绪" if self.language == "zh" else "Ready")

    def applyTheme(self):
        if self.is_dark_theme:
            self.setStyleSheet(DARK_THEME_CSS)
        else:
            self.setStyleSheet(LIGHT_THEME_CSS)
        self.applyProgressBarTheme()  # 确保导出进度条样式更新
        self.applySliderTheme()  # 确保视频播放进度条样式更新

    def setTheme(self, is_dark):
        self.is_dark_theme = is_dark
        self.applyTheme()

    def setLanguage(self, language):
        translator = QTranslator()
        if language == "zh":
            translator.load("zh_CN.qm")
        else:
            translator.load("en_US.qm")
        QApplication.instance().installTranslator(translator)
        self.language = language
        self.updateUI()

    def updateUI(self):
        self.menuBar().clear()
        self.createMenuBar()
        if hasattr(self, 'play_button'):
            self.play_button.setText("播放" if self.language == "zh" else "Play")
        if hasattr(self, 'pause_button'):
            self.pause_button.setText("暂停" if self.language == "zh" else "Pause")
        if hasattr(self, 'rewind_button'):
            self.rewind_button.setText("快退3s" if self.language == "zh" else "Rewind 3s")
        if hasattr(self, 'forward_button'):
            self.forward_button.setText("快进3s" if self.language == "zh" else "Forward 3s")
        dock = self.findChild(QDockWidget)
        if dock:
            dock.setWindowTitle("GIF 导出设置" if self.language == "zh" else "GIF Export Settings")
            side_widget = dock.widget()
            if side_widget:
                form_layout = side_widget.layout()
                if form_layout:
                    for i in range(form_layout.rowCount()):
                        item = form_layout.itemAt(i, QFormLayout.LabelRole)
                        if item is not None:
                            label = item.widget()
                            if label:
                                if label.text().startswith("起始秒数"):
                                    label.setText("起始秒数:" if self.language == "zh" else "Start Second:")
                                elif label.text().startswith("结束秒数"):
                                    label.setText("结束秒数:" if self.language == "zh" else "End Second:")
                                elif label.text().startswith("宽度"):
                                    label.setText("宽度:" if self.language == "zh" else "Width:")
                                elif label.text().startswith("高度"):
                                    label.setText("高度:" if self.language == "zh" else "Height:")
                                elif label.text().startswith("帧数"):
                                    label.setText("帧数:" if self.language == "zh" else "Frames:")
                                elif label.text().startswith("FPS"):
                                    label.setText("FPS:" if self.language == "zh" else "FPS:")
        if hasattr(self, 'export_button'):
            self.export_button.setText("导出GIF" if self.language == "zh" else "Export GIF")
        if hasattr(self, 'cancel_button'):
            self.cancel_button.setText("取消导出" if self.language == "zh" else "Cancel Export")
        if hasattr(self, 'optimize_checkbox'):
            self.optimize_checkbox.setText("优化 GIF" if self.language == "zh" else "Optimize GIF")
        self.status_bar.showMessage("就绪" if self.language == "zh" else "Ready")

    def toggleFullScreen(self):
        if self.isFullScreen():
            self.showNormal()
        else:
            self.showFullScreen()

    def play_pause_video(self):
        if self.timer.isActive():
            self.pause_video()
        else:
            self.play_video()

    def upload_video(self):
        self.video_path, _ = QFileDialog.getOpenFileName(
            self, "选择视频文件" if self.language == "zh" else "Select Video File", "",
            "Video Files (*.mp4 *.avi *.mov *.mkv *.flv *.webm *.wmv *.gif)"
        )
        if not self.video_path:
            QMessageBox.warning(self, "错误", "未选择视频文件")
            return
        if not os.path.exists(self.video_path):
            QMessageBox.warning(self, "错误", "视频文件不存在")
            return
        self.cap = cv2.VideoCapture(self.video_path)
        if not self.cap.isOpened():
            QMessageBox.warning(self, "错误", "无法打开视频文件")
            return
        self.total_frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
        self.fps = self.cap.get(cv2.CAP_PROP_FPS)
        self.frame_cache = LRUCache(max(200, int(self.total_frames * 0.1)))
        self.slider.setRange(0, self.total_frames)
        self.pause_video()
        self.show_frame_at(0)

    def play_video(self):
        if self.cap is not None:
            self.timer.timeout.connect(self.update_frame)
            self.timer.start(int(1000 / self.fps))

    def pause_video(self):
        self.timer.stop()

    def reset_video(self):
        if self.cap is not None:
            self.current_frame = 0
            self.cap.set(cv2.CAP_PROP_POS_FRAMES, self.current_frame)
            self.slider.setValue(self.current_frame)
            self.show_frame_at(self.current_frame)
            self.pause_video()

    def rewind_video(self):
        if self.cap is not None:
            self.current_frame = max(0, self.current_frame - int(3 * self.fps))
            self.cap.set(cv2.CAP_PROP_POS_FRAMES, self.current_frame)
            self.slider.setValue(self.current_frame)
            self.show_frame_at(self.current_frame)

    def forward_video(self):
        if self.cap is not None:
            self.current_frame = min(self.total_frames, self.current_frame + int(3 * self.fps))
            self.cap.set(cv2.CAP_PROP_POS_FRAMES, self.current_frame)
            self.slider.setValue(self.current_frame)
            self.show_frame_at(self.current_frame)

    def slider_pressed(self):
        self.is_slider_pressed = True
        self.pause_video()

    def slider_released(self):
        self.is_slider_pressed = False
        self.set_position(self.slider.value())

    def slider_moved(self, position):
        if self.is_slider_pressed:
            self.show_frame_at(position)

    def slider_mouse_press_event(self, event):
        if self.cap is not None:
            pos = event.pos().x()
            frame_pos = int((pos / self.slider.width()) * self.total_frames)
            self.set_position(frame_pos)
            self.slider.setValue(frame_pos)
            self.show_frame_at(frame_pos)

    def set_position(self, position):
        if self.cap is not None:
            self.current_frame = position
            self.cap.set(cv2.CAP_PROP_POS_FRAMES, self.current_frame)
            self.slider.setValue(self.current_frame)
            self.show_frame_at(self.current_frame)

    def show_frame_at(self, position):
        if self.cap is not None:
            frame = self.frame_cache.get(position)
            if frame is None:
                self.cap.set(cv2.CAP_PROP_POS_FRAMES, position)
                ret, frame = self.cap.read()
                if ret:
                    self.frame_cache.put(position, frame)
                else:
                    return
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            label_size = self.video_label.size()
            h, w, _ = frame.shape
            aspect_ratio = w / h
            new_width = label_size.width()
            new_height = int(new_width / aspect_ratio)
            frame = cv2.resize(frame, (new_width, new_height))
            bytes_per_line = 3 * new_width
            q_img = QImage(frame.data, new_width, new_height, bytes_per_line, QImage.Format_RGB888)
            self.video_label.setPixmap(QPixmap.fromImage(q_img))

    def resizeEvent(self, event):
        super().resizeEvent(event)
        if self.cap is not None:
            self.update_video_size()

    def changeEvent(self, event):
        super().changeEvent(event)
        if event.type() == event.WindowStateChange:
            if self.windowState() & Qt.WindowMaximized:
                self.update_video_size()
            elif self.windowState() & Qt.WindowNoState:
                self.update_video_size()
            elif self.windowState() & Qt.WindowMinimized:
                pass

    def update_video_size(self):
        if self.cap is not None:
            self.show_frame_at(self.current_frame)

    def update_frame(self):
        if self.cap is not None and not self.is_slider_pressed:
            ret, frame = self.cap.read()
            if ret:
                self.current_frame += 1
                self.slider.setValue(self.current_frame)
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                label_size = self.video_label.size()
                h, w, _ = frame.shape
                aspect_ratio = w / h
                new_width = label_size.width()
                new_height = int(new_width / aspect_ratio)
                frame = cv2.resize(frame, (new_width, new_height))
                bytes_per_line = 3 * new_width
                q_img = QImage(frame.data, new_width, new_height, bytes_per_line, QImage.Format_RGB888)
                self.video_label.setPixmap(QPixmap.fromImage(q_img))
            else:
                self.timer.stop()

    def export_gif(self):
        if not self.video_path:
            QMessageBox.warning(self, "错误", "请先上传视频文件")
            return
        try:
            start_second = float(self.start_second_input.text())
            end_second = float(self.end_second_input.text())
            width = int(self.width_input.text())
            height = int(self.height_input.text())
            frames = int(self.frames_input.text())
            fps = int(self.fps_input.text())
            optimize = self.optimize_checkbox.isChecked()
            if width <= 0 or height <= 0:
                QMessageBox.warning(self, "错误", "宽度和高度必须大于 0")
                return
            if start_second >= end_second:
                QMessageBox.warning(self, "错误", "起始秒数必须小于结束秒数")
                return
            start_frame = int(start_second * self.fps)
            end_frame = int(end_second * self.fps)
            progress_range = max(1, end_frame - start_frame)
            self.export_progress.setRange(0, progress_range)
            self.export_progress.setValue(0)
            self.export_thread = ExportGifThread(
                self.video_path, start_frame, end_frame, width, height, frames, fps, optimize
            )
            self.export_thread.progress_signal.connect(self.export_progress.setValue)
            self.export_thread.finished_signal.connect(self.export_finished)
            self.export_thread.error_signal.connect(self.export_error)
            self.export_thread.start()
            self.export_button.setEnabled(False)
            self.cancel_button.setEnabled(True)
        except ValueError:
            QMessageBox.warning(self, "错误", "请输入有效的参数")

    def export_finished(self, gif_path):
        self.export_button.setEnabled(True)
        self.cancel_button.setEnabled(False)
        QMessageBox.information(self, "成功", f"GIF已导出到: {gif_path}")

    def export_error(self, error_msg):
        self.export_button.setEnabled(True)
        self.cancel_button.setEnabled(False)
        QMessageBox.warning(self, "错误", error_msg)

    def cancel_export(self):
        if self.export_thread and self.export_thread.isRunning():
            self.export_thread.cancel()
            self.export_thread.terminate()
            self.export_thread.wait()
            self.export_button.setEnabled(True)
            self.cancel_button.setEnabled(False)
            self.export_progress.setValue(0)
            QMessageBox.information(self, "取消", "导出已取消")




